<script setup>

import MyTable from "@/common/myTable.vue";
import CardArea from "@/components/cardArea.vue";
import {onMounted, ref} from "vue";
import {deleteAdmin, getAdmin} from "@/api/admin.js";
import {ElMessage, ElMessageBox} from "element-plus";
import AdminForm from "@/views/admin/admin-form.vue";
import AdminSearch from "@/views/admin/admin-search.vue";

const ids = ref([])

const pageData = ref({
  list: [],
  total: undefined,
})

//搜索条件
const searchData = ref({
  page: 1,
  size: 10,
})
//获取列表
const getList = async () => {
  const {data, code, msg} = await getAdmin(searchData.value)
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  pageData.value = data
}
//删除
const del = async (id) => {
  ElMessageBox.confirm(
      '是否删除此用户？',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {code, msg} = await deleteAdmin(id)
        if (code !== 200) {
          ElMessage.error(msg)
          return
        }
        ElMessage.success(msg)
        await getList()
      })
      .catch(() => {
        ElMessage.info('已取消')
      })
}
//要修改的用户id
const id = ref(undefined)
//操作开关
const actionFlag = ref(false)

onMounted(() => {
  getList()
})

const columns = [
  {key: 'selection', type: 'selection', width: '55px'},
  {key: 'id', title: 'id'},
  {key: 'account', title: '账号'},
  {key: 'nickname', title: '昵称'},
  {key: 'avatar', title: '头像', type: 'img'},
  {key: 'createdTime', title: '创建时间', width: '220px'},
  {key: 'updatedTime', title: '修改时间', width: '220px'},
  {key: 'action', title: '操作'},
]
</script>

<template>
  <!--表单操作处-->
  <el-dialog width="500" v-if="actionFlag" v-model="actionFlag" :before-close="() => {id=undefined;actionFlag = false}">
    <template #header>
      <div style="text-align: center;margin-bottom: 20px">
        <h1>{{ id ? '修改管理员' : '新增管理员' }}</h1>
      </div>
    </template>
    <admin-form :id="id" @success="() => {actionFlag = false;id=undefined;getList()}"/>
  </el-dialog>
  <!--表格数据显示的地方-->
  <card-area title="管理员管理">
    <template #search>
      <admin-search v-model:search-data="searchData" @search="getList"/>
    </template>

    <my-table v-model:search-data="searchData" :list="pageData.list" :columns="columns" :total="pageData.total"
              @selectionChange="args => {
      ids = args
    }" @load="getList">
      <template #created>
        <el-button theme @click="actionFlag = true">新增管理员</el-button>
      </template>

      <template #action="{row}">
        <el-button type="warning" plain @click="() => {id = row.id;actionFlag = true}">编辑</el-button>
        <el-button type="danger" plain @click="del(row.id)">删除</el-button>
      </template>

    </my-table>

  </card-area>
</template>

<style scoped lang="scss">

</style>
